﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using iTextSharp.text.pdf;
using System.Diagnostics;
using System.IO;
using iTextSharp.text;
using System.Text;

namespace iTextPdfReadTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        const string PDF = "PDFs/ASM454.pdf";
        int pageNumber = 0;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        PdfReader reader;
        //PdfReaderContentParser parser;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            pageNumber = 0;
            readNextPage();

        }

        private void readNextPage()
        {

            var strm = App.GetResourceStream(new Uri("/iTextPdfReadTest;Component/" + PDF, UriKind.Relative));
            
            try
            {
                reader = new PdfReader(strm.Stream);
                PdfDictionary page = reader.GetPageN(pageNumber+1);
                PRIndirectReference objectReference = (PRIndirectReference)page.Get(PdfName.CONTENTS);
                PRStream stream = (PRStream)PdfReader.GetPdfObject(objectReference);
                byte[] streamBytes = PdfReader.GetStreamBytes(stream);
                String contentStream = System.Text.Encoding.UTF8.GetString(streamBytes, 0, streamBytes.Length);
                Debug.WriteLine(contentStream);
                PRTokeniser tokenizer = new PRTokeniser(streamBytes);
                while (tokenizer.NextToken()) {
                    if (tokenizer.TokenType == PRTokeniser.TK_NAME)
                    {
                        Debug.WriteLine("Name: " + tokenizer.StringValue);
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_STRING) {
                        Debug.WriteLine("String: " + tokenizer.StringValue);
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_COMMENT)
                    {
                        Debug.WriteLine("Comment: " + tokenizer.StringValue);
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_NUMBER)
                    {
                        Debug.WriteLine("Number: " + tokenizer.StringValue);
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_OTHER)
                    {
                        Debug.WriteLine("Other: ");
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_START_ARRAY)
                    {
                        Debug.WriteLine("Start Array: ");
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_END_ARRAY)
                    {
                        Debug.WriteLine("End Array: ");
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_START_DIC)
                    {
                        Debug.WriteLine("Start Dict: ");
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_END_DIC)
                    {
                        Debug.WriteLine("End Dict: ");
                    }
                    if (tokenizer.TokenType == PRTokeniser.TK_REF)
                    {
                        Debug.WriteLine("Ref: ");
                    }
                    
				}
			    // we do some dirty hacking, replacing Hello World by something else
			    //var buf = new StringBuilder();
			    //int pos = contentStream.IndexOf("Hello World") + 11;
			    //buf.append(contentStream.substring(0, pos));
			    //buf.append(", Hello Sun, Hello Moon, Hello Stars, Hello Universe");
			    //buf.append(contentStream.substring(pos));
			    //String hackedContentStream = buf.toString();
			    // we create a new PDF file that contains the hacked stream
			    //Document document = new Document(PageSize.A6);
			    //PdfWriter writer = PdfWriter.getInstance(document,
				//        new FileOutputStream("results/in_action/chapter18/HelloWorldStreamHacked.pdf"));
			    //document.open();
			    //PdfContentByte cb = writer.getDirectContent();
			    //cb.setLiteral(hackedContentStream);
			    //document.close();
		    } catch (IOException e) {
			    //e.printStackTrace();
                Debug.WriteLine("IO Error");
		    } catch (DocumentException e) {
			    //e.printStackTrace();
                Debug.WriteLine("Doc Error");
		    }
            finally
            {
                if (reader != null)
                    reader.Close();
                reader = null;
            }
        }
    }
}